package com.bill99.rpc.protocol.hessian;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.remoting.caucho.HessianExporter;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.util.NestedServletException;

/**
 * @author sheng.zhang
 * 
 */
public class HessianProtocolBean extends HessianExporter implements
		HttpRequestHandler, InitializingBean, ApplicationContextAware {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	protected ApplicationContext applicationContext = null;
	protected String name;
	protected String path;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (!"POST".equals(request.getMethod()))
			throw new HttpRequestMethodNotSupportedException(
					request.getMethod(), new String[] { "POST" },
					"HessianServiceExporter only supports POST requests");
		try {
			invoke(request.getInputStream(), response.getOutputStream());
		} catch (Throwable ex) {
			throw new NestedServletException(
					"Hessian skeleton invocation failed", ex);
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public void afterPropertiesSet() {
	}
}
